<template>
	<view class="container">
		<!-- Loading 状态 -->
		<view class="loading-wrapper" v-if="pageLoading">
			<uni-load-more status="loading" :content-text="loadingText"></uni-load-more>
		</view>
		
		<view class="edit-form" v-else>
			<!-- 标题输入 -->
			<view class="form-item">
				<view class="form-label">
					<text class="label-text">标题</text>
					<text class="required">*</text>
				</view>
				<input 
					class="title-input"
					type="text"
					v-model="postForm.title"
					placeholder="请输入标题(最多50字)"
					maxlength="50"
				/>
				<text class="count" :class="{ 'warning': postForm.title.length >= 45 }">
					{{ postForm.title.length }}/50
				</text>
			</view>
			
			<!-- 内容输入 -->
			<view class="form-item">
				<view class="form-label">
					<text class="label-text">内容</text>
					<text class="required">*</text>
				</view>
				<textarea
					class="content-input"
					v-model="postForm.content"
					placeholder="请输入内容(最多2000字)"
					maxlength="2000"
					:auto-height="true"
				></textarea>
				<text class="count" :class="{ 'warning': postForm.content.length >= 1900 }">
					{{ postForm.content.length }}/2000
				</text>
			</view>
			
			<!-- 分类选择 -->
			<view class="form-item">
				<view class="form-label">
					<text class="label-text">分类</text>
					<text class="required">*</text>
				</view>
				<picker 
					:value="categoryIndex" 
					:range="categories" 
					range-key="name"
					@change="handleCategoryChange"
				>
					<view class="picker">
						<text class="value">{{ postForm.category?.name || '请选择分类' }}</text>
						<uni-icons type="right" size="16" color="#999"></uni-icons>
					</view>
				</picker>
				<text class="tip">选择合适的分类更容易被发现</text>
			</view>
			
			<!-- 封面组件 -->
			<view class="form-item">
				<view class="form-label">
					<text class="label-text">封面</text>
					<text class="tip-text">(可选)</text>
				</view>
				
				<view class="cover-upload">
					<!-- 显示已选封面 -->
					<view class="cover-preview" v-if="coverPreview || postForm.cover">
						<image 
							:src="coverPreview || (api.BASE_URL + postForm.cover)"
							mode="aspectFill" 
							class="cover-image"
							@tap="previewImage"
						></image>
						<view class="cover-mask">
							<view class="action-btns">
								<view class="action-btn" @tap.stop="changeCover">
									<uni-icons type="reload" size="20" color="#fff"></uni-icons>
									<text>更换</text>
								</view>
								<view class="action-btn delete" @tap.stop="removeCover">
									<uni-icons type="trash" size="20" color="#fff"></uni-icons>
									<text>删除</text>
								</view>
							</view>
						</view>
					</view>
					
					<!-- 上传按钮 -->
					<view 
						class="upload-btn" 
						v-else
						@tap="changeCover"
					>
						<uni-icons type="camera-filled" size="32" color="#999"></uni-icons>
						<text>添加封面</text>
					</view>
				</view>
				<text class="tip">建议尺寸 800x400,大小不超过2MB</text>
			</view>
			
			<!-- 置顶选项 -->
			<view class="form-item switch-item">
				<view class="switch-left">
					<text class="label-text">置顶帖子</text>
					<text class="tip">置顶后会显示在列表顶部</text>
				</view>
				<switch 
					:checked="postForm.is_pinned"
					@change="handlePinnedChange"
					color="#007AFF"
				/>
			</view>
		</view>
		
		<!-- 底部按钮 -->
		<view class="bottom-btns">
			<button 
				class="submit-btn"
				:disabled="!isValid || submitting"
				@tap="handleSubmit"
			>
				{{ submitting ? '保存中...' : '保存修改' }}
			</button>
		</view>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { api } from '@/utils/request'
import { onLoad } from '@dcloudio/uni-app'
import Storages from '@/utils/storages'

// 页面加载状态
const pageLoading = ref(true)
const loadingText = {
	contentdown: '上拉显示更多',
	contentrefresh: '加载中...',
	contentnomore: '没有更多数据了'
}

// 表单数据
const postForm = ref({
	id: '',
	title: '',
	content: '',
	category: null,
	is_pinned: false,
	cover: ''
})

// 分类相关
const categories = ref([])
const categoryIndex = ref(-1)

// 提交状态
const submitting = ref(false)

// 帖子ID
const postId = ref('')

// 添加本地预览图片路径
const coverPreview = ref('')
// 添加临时文件路径
const tempCoverPath = ref('')

// 添加用户信息
const userInfo = ref(null)

// 表单验证
const isValid = computed(() => {
	return postForm.value.title.trim() && 
		   postForm.value.content.trim() && 
		   postForm.value.category
})

// 获取帖子详情
const getPostDetail = async () => {
	try {
		const res = await api.request({
			url: '/api/post/get_post_detail/',
			method: 'GET',
			data: {
				post_id: postId.value
			}
		})
		
		if(res.code === 200) {
			// 填充表单数据
			postForm.value = {
				id: res.data.id,
				title: res.data.title,
				content: res.data.content,
				category: res.data.category,
				is_pinned: res.data.is_pinned,
				cover: res.data.cover
			}
			
			// 设置分类索引
			categoryIndex.value = categories.value.findIndex(
				cat => cat.id === res.data.category.id
			)
		}
	} catch(err) {
		console.error('获取帖子详情失败', err)
		uni.showToast({
			title: '获取帖子详情失败',
			icon: 'none'
		})
	} finally {
		pageLoading.value = false
	}
}

// 获取分类列表
const getCategories = async () => {
	try {
		const res = await api.request({
			url: '/api/post/get_category/',
			method: 'GET'
		})
		
		if(res.code === 200) {
			categories.value = res.data
		}
	} catch(err) {
		console.error('获取分类列表失败', err)
	}
}

// 处理分类变化
const handleCategoryChange = (e) => {
	categoryIndex.value = e.detail.value
	postForm.value.category = categories.value[categoryIndex.value]
}

// 处理置顶状态变化
const handlePinnedChange = (e) => {
	postForm.value.is_pinned = e.detail.value
}

// 预览图片
const previewImage = () => {
	const previewUrl = coverPreview.value || (api.BASE_URL + postForm.value.cover)
	if(!previewUrl) return
	uni.previewImage({
		urls: [previewUrl]
	})
}

// 更换封面
const changeCover = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: async (res) => {
			const filePath = res.tempFilePaths[0]
			
			// 检查文件大小
			const fileInfo = await uni.getFileInfo({
				filePath: filePath
			})
			
			if(fileInfo.size > 2 * 1024 * 1024) { // 2MB
				uni.showToast({
					title: '图片大小不能超过2MB',
					icon: 'none'
				})
				return
			}
			
			// 保存临时文件路径
			tempCoverPath.value = filePath
			// 设置预览图片
			coverPreview.value = filePath
		}
	})
}

// 删除封面
const removeCover = () => {
	uni.showModal({
		title: '提示',
		content: '确定要删除封面吗？',
		success: (res) => {
			if(res.confirm) {
				// 清除预览和临时文件
				coverPreview.value = ''
				tempCoverPath.value = ''
				// 标记需要删除原封面
				if(postForm.value.cover) {
					postForm.value.cover = 'delete'
				}
			}
		}
	})
}

// 获取用户信息
const getUserInfo = () => {
	const info = uni.getStorageSync(Storages.UserInfo.userInfo)
	if(info) {
		userInfo.value = info
	} else {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		setTimeout(() => {
			uni.navigateBack()
		}, 1500)
	}
}

// 修改提交表单方法
const handleSubmit = async () => {
	if(!isValid.value || submitting.value) return
	if(!userInfo.value) {
		uni.showToast({
			title: '请先登录',
			icon: 'none'
		})
		return
	}
	
	submitting.value = true
	try {
		const formData = {
			post_id: postForm.value.id,
			title: postForm.value.title.trim(),
			content: postForm.value.content.trim(),
			category: postForm.value.category.id,
			user_id: userInfo.value.user_id,
		}
		
		// 使用Promise包装uni.uploadFile
		const uploadResult = await new Promise((resolve, reject) => {
			uni.uploadFile({
				url: api.BASE_URL + '/api/post/edit_post/',
				// 如果有新选择的封面就上传文件,否则不上传
				filePath: tempCoverPath.value,
				name: 'cover',
				formData: formData,
				success: (uploadRes) => {
					resolve(uploadRes)
				},
				fail: (err) => {
					reject(err)
				}
			})
		})
		
		const result = JSON.parse(uploadResult.data)
		if(result.code === 200) {
			uni.showToast({
				title: '修改成功',
				icon: 'success'
			})
			
			setTimeout(() => {
				uni.navigateBack()
			}, 1500)
		} else {
			throw new Error(result.message || '修改失败')
		}
	} catch(err) {
		console.error('提交失败', err)
		uni.showToast({
			title: err.message || '修改失败',
			icon: 'none'
		})
	} finally {
		submitting.value = false
	}
}

onLoad((options) => {
	if(!options.post_id) {
		uni.navigateBack()
		return
	}
	postId.value = options.post_id
	
	// 先获取用户信息
	getUserInfo()
	
	// 再获取其他数据
	if(userInfo.value) {
		Promise.all([
			getCategories(),
			getPostDetail()
		])
	}
})
</script>

<style lang="scss" scoped>
.container {
	min-height: 100vh;
	background: #f5f5f5;
	padding: 20rpx;
	padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
	box-sizing: border-box;
}

.loading-wrapper {
	min-height: 100vh;
	display: flex;
	align-items: center;
	justify-content: center;
	background: #fff;
}

.edit-form {
	background: #fff;
	border-radius: 12rpx;
	padding: 30rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
	
	.form-item {
		position: relative;
		margin-bottom: 40rpx;
		
		.form-label {
			display: flex;
			align-items: center;
			margin-bottom: 16rpx;
			
			.label-text {
				font-size: 28rpx;
				color: #333;
				font-weight: bold;
			}
			
			.required {
				color: #ff6b6b;
				margin-left: 8rpx;
			}
		}
		
		.title-input {
			width: 100%;
			height: 88rpx;
			background: #f8f8f8;
			border-radius: 12rpx;
			padding: 0 30rpx;
			font-size: 32rpx;
			color: #333;
			box-sizing: border-box;
		}
		
		.content-input {
			width: 100%;
			min-height: 300rpx;
			max-height: 600rpx;
			background: #f8f8f8;
			border-radius: 12rpx;
			padding: 20rpx 30rpx;
			font-size: 28rpx;
			color: #333;
			line-height: 1.6;
			box-sizing: border-box;
		}
		
		.count {
			position: absolute;
			bottom: -30rpx;
			right: 0;
			font-size: 24rpx;
			color: #999;
			
			&.warning {
				color: #ff6b6b;
			}
		}
		
		.picker {
			display: flex;
			align-items: center;
			height: 88rpx;
			background: #f8f8f8;
			border-radius: 12rpx;
			padding: 0 30rpx;
			
			.value {
				flex: 1;
				font-size: 28rpx;
				color: #333;
			}
		}
		
		.tip {
			font-size: 24rpx;
			color: #999;
			margin-top: 8rpx;
			display: block;
		}
		
		&.switch-item {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 20rpx 30rpx;
			background: #f8f8f8;
			border-radius: 12rpx;
			
			.switch-left {
				.label-text {
					font-size: 28rpx;
					color: #333;
					margin-bottom: 8rpx;
					display: block;
				}
				
				.tip {
					margin-top: 0;
				}
			}
		}
	}
}

.bottom-btns {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 0;
	background: #fff;
	padding: 20rpx;
	padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.04);
	
	.submit-btn {
		width: 100%;
		height: 88rpx;
		line-height: 88rpx;
		background: #007AFF;
		color: #fff;
		font-size: 32rpx;
		border-radius: 44rpx;
		margin: 0;
		
		&:disabled {
			opacity: 0.5;
			background: #ccc;
		}
		
		&:active {
			opacity: 0.8;
		}
	}
}

.cover-upload {
	width: 100%;
	height: 400rpx;
	background: #f8f8f8;
	border-radius: 12rpx;
	overflow: hidden;
	position: relative;
	
	.cover-preview {
		width: 100%;
		height: 100%;
		position: relative;
		
		.cover-image {
			width: 100%;
			height: 100%;
			display: block;
		}
		
		.cover-mask {
			position: absolute;
			left: 0;
			right: 0;
			bottom: 0;
			padding: 20rpx;
			background: linear-gradient(to top, rgba(0,0,0,0.5), transparent);
			
			.action-btns {
				display: flex;
				justify-content: flex-end;
				gap: 20rpx;
				
				.action-btn {
					display: flex;
					align-items: center;
					gap: 8rpx;
					padding: 12rpx 24rpx;
					background: rgba(255,255,255,0.2);
					border-radius: 30rpx;
					
					text {
						color: #fff;
						font-size: 24rpx;
					}
					
					&:active {
						opacity: 0.8;
					}
					
					&.delete {
						background: rgba(255,107,107,0.3);
					}
				}
			}
		}
	}
	
	.upload-btn {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		gap: 16rpx;
		
		text {
			font-size: 28rpx;
			color: #999;
		}
		
		&:active {
			background: #f0f0f0;
		}
	}
}

.tip-text {
	font-size: 24rpx;
	color: #999;
	margin-left: 8rpx;
	font-weight: normal;
}
</style>
